package com.yh.service.impl;

import com.yh.entity.UserInfo;
import com.yh.mapper.UserInfoMapper;
import com.yh.service.RedisLock;
import com.yh.util.RedisLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author yh
 */
@Service
@Slf4j
public class RedisLockImpl implements RedisLock {
    private RedissonClient redissonClient;
    private UserInfoMapper userInfoMapper;
    private RedisLockUtil redisLockUtil;
    private static  final String LOCK_NAME = "REDIS_USER_LOCK";

    public RedisLockImpl(RedissonClient redissonClient,UserInfoMapper userInfoMapper,RedisLockUtil redisLockUtil){
        this.redissonClient = redissonClient;
        this.userInfoMapper = userInfoMapper;
        this.redisLockUtil = redisLockUtil;
    }

    @Override
    public void updateUserInfoRedis(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        RLock lock = redissonClient.getLock(LOCK_NAME);
        boolean locked = false;
        try {
            locked = lock.tryLock(1,60,TimeUnit.SECONDS);
            if(!locked){
                log.info("服务器繁忙，请稍后再试！!!");
            }
            //操作用户钱包
            if(userInfo.getPrice().compareTo(new BigDecimal("0")) > -1){
                userInfo.setPrice(userInfo.getPrice().subtract(new BigDecimal("1")));
            }
            userInfoMapper.updateById(userInfo);
        } catch (Exception e) {
            log.info("服务器繁忙，请稍后再试！");
        } finally {
            lock.unlock();
        }

    }
}
